package com.mio.web.service.user;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
import java.util.Random;

import org.durcframework.core.expression.ExpressionQuery;
import org.durcframework.core.expression.subexpression.ValueExpression;
import org.durcframework.core.service.CrudService;
import org.springframework.stereotype.Service;

import com.mio.web.dao.user.UserDao;
import com.mio.web.entity.user.User;
import com.mio.web.util.mail.MailSenderInfo;
import com.mio.web.util.mail.SimpleMailSender;
import com.mio.web.common.Md5Encrypt;
import com.mio.web.util.PasswordUtil;

@Service
public class UserService extends CrudService<User, UserDao> {

	public User getUserByUserName(String userName) {
		ExpressionQuery query = new ExpressionQuery();

		query.add(new ValueExpression("userName", userName));
		query.add(new ValueExpression("isDeleted", false));
		List<User> list = getDao().find(query);
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	public boolean sendEmail(User user) throws IOException {
		Properties prop = new Properties();
		InputStream is = this.getClass().getClassLoader().getResourceAsStream("email.properties");
		prop.load(is);
		user = this.getDao().get(user.getId());
		MailSenderInfo mailInfo = new MailSenderInfo();
		mailInfo.setMailServerHost(prop.getProperty("host"));
		mailInfo.setMailServerPort(prop.getProperty("port"));
		mailInfo.setValidate(true);
		mailInfo.setUserName(prop.getProperty("userName")); // 自己的邮箱
		mailInfo.setPassword(prop.getProperty("password")); // 发件人邮箱的登录密码
		mailInfo.setFromAddress(prop.getProperty("userName")); /// 自己的邮箱
		mailInfo.setToAddress(user.getEmail()); /// 对方的邮箱
		
//		mailInfo.setUserName("13862389729@163.com"); // 自己的邮箱
//		mailInfo.setPassword("gsj53452827"); // 发件人邮箱的登录密码
//		mailInfo.setFromAddress("13862389729@163.com"); /// 自己的邮箱
//		mailInfo.setToAddress("1316833885@qq.com"); /// 对方的邮箱
//		mailInfo.setSubject("美爱我"+user.getId());
		// 随机一个6位数密码
		Random random = new Random();
		int randomPwd = random.nextInt(899999);
		randomPwd = randomPwd + 100000;
		String hashCodePwd = PasswordUtil.createHash(Md5Encrypt.encrypt(String.valueOf(randomPwd)));
		mailInfo.setContent("您的密码为:"+randomPwd);

		// 修改用户信息
		user.setPassword(hashCodePwd);
		user = this.update(user);

		// 这个类主要来发送邮件
		SimpleMailSender sms = new SimpleMailSender();
		return sms.sendTextMail(mailInfo);// 发送文体格式
	}

}